package com.ics.atable.chat.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static com.alibaba.cloud.ai.graph.StateGraph.END;
import static com.ics.atable.chat.constant.ItemQueryConstant.*;

@Slf4j
public class HumanFeedbackNode implements NodeAction {

    @Override
    public Map<String, Object> apply(OverAllState state) throws Exception {
        Map<String, Object> updated = new HashMap<>();

        // 人类反馈结点数据部分收集
        Map<String, Object> feedBackData = state.humanFeedback().data();
        Boolean feedback = (Boolean) feedBackData.getOrDefault("feedback", true);
        String feedbackContent = feedBackData.getOrDefault("feedback_content", "").toString();

        updated.put("feedback", feedback);
        updated.put("feedback_content", feedbackContent);

        Integer feedbackCount = state.value(FEED_BACK_COUNT, 0);
        if (feedbackCount == null) {
            feedbackCount = 0;
        }
        feedbackCount += 1;
        updated.put(FEED_BACK_COUNT, feedbackCount);
        log.info("feedbackCount: {}", feedbackCount);

        // 若没有反馈或者反馈次数超过5次则直接结束
        if (!feedback && feedbackCount <= 5) {
            updated.put(HUMAN_FEEDBACK_NEXT_NODE, INTENT);
        }
        else{
            updated.put(HUMAN_FEEDBACK_NEXT_NODE, END);
        }


        return updated;
    }
}
